package cos.parser;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import cos.entity.LyricsResponse;
import cos.entity.ParserName;
import cos.entity.Song;

public class ParsingManager {

	private final Parser[] parsers;

	private int currentParser;

	/**
	 * add all the parsers we have
	 */
	public ParsingManager() {
		Parser[] temp = { new LocalArchiveParser(), new LyricsWikiaParser(),
				new DarkLyricsParser(), new LyricsManiaParser() };
		parsers = temp;
	}

	/**
	 * first request for song lyrics
	 */
	public LyricsResponse getLyrics(Song song) {
		currentParser = 0;
		return getLyrics(0, song);
	}

	/**
	 * try to get another lyrics variant
	 */
	/*
	 * public String getMoreLyrics(Song song) { if (!hasMoreVariants()) return
	 * null; return getLyrics(currentParser + 1, song); }
	 */

	/**
	 * search lyrics till we get some
	 */
	private LyricsResponse getLyrics(int startFrom, Song song) {

		for (int i = startFrom; i < parsers.length; i++) {
			LyricsResponse resp = parsers[i].getLyrics(song);
			if (resp != null && resp.getLyrics() != null) {
				String out = resp.getLyrics();
				currentParser = i;

				// ololo KOSTYLI:
				// if it isn't localParser, save lyrics to local folder
				if (resp.getParserName() != ParserName.LOCAL)
					saveLyricsToLocal(song, out);

				return resp;
			}
		}

		return null; // nothing is finded
	}

	/**
	 * lets make a thread, that will save song lyrics to a local archive
	 */
	private void saveLyricsToLocal(Song song, String lyrics) {
		new Thread(new SaveLyrics(song, lyrics)).start();
	}

	/**
	 * if we didn't check all the parsers already
	 */
	public boolean hasMoreVariants() {
		return currentParser < parsers.length;
	}
}

/**
 * thread class used to save lyrics in local archive
 */
class SaveLyrics implements Runnable {

	private final Song song;
	private final String lyrics;

	public SaveLyrics(Song song, String lyrics) {
		this.song = song;
		this.lyrics = lyrics;
	}

	@Override
	public void run() {
		synchronized (this) {
			BufferedWriter out = null;
			try {
				// folder name
				String fileName = "lyrics/" + song.getArtistForFile();
				File file = new File(fileName);
				if (!file.exists())
					file.mkdirs(); // make folder if not exist

				// txt file name
				fileName = fileName + "/" + song.getTitleForFile() + ".txt";
				file = new File(fileName);
				if (!file.exists()) {
					boolean exist = file.createNewFile(); // if we made it
					if (exist) {
						FileWriter fstream = new FileWriter(fileName);
						out = new BufferedWriter(fstream);
						out.write(lyrics);
					}
				}
			} catch (IOException e) {
			} finally {
				if (out != null)
					try {
						out.close();
					} catch (IOException e) {
					}
			}
		}
	}
}
